package com.engine4cloud.tdf.supervision.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.engine4cloud.tdf.admin.api.entity.SysDept;
import com.engine4cloud.tdf.admin.api.feign.RemoteDeptService;
import com.engine4cloud.tdf.common.core.constant.SecurityConstants;
import com.engine4cloud.tdf.common.core.exception.ValidateCodeException;
import com.engine4cloud.tdf.common.core.util.R;
import com.engine4cloud.tdf.common.core.util.RetOps;
import com.engine4cloud.tdf.common.data.web.query.Pages;
import com.engine4cloud.tdf.common.data.web.query.Queries;
import com.engine4cloud.tdf.common.data.web.response.PageInfo;
import com.engine4cloud.tdf.common.data.web.response.Params;
import com.engine4cloud.tdf.common.security.service.TdfUser;
import com.engine4cloud.tdf.common.security.util.SecurityUtils;
import com.engine4cloud.tdf.supervision.convert.GzrySocialWorkerConvert;
import com.engine4cloud.tdf.supervision.dto.IdentityUniqueCheckDTO;
import com.engine4cloud.tdf.supervision.dto.MobileUniqueCheckDTO;
import com.engine4cloud.tdf.supervision.dto.create.GzrySocialWorkerCreateDTO;
import com.engine4cloud.tdf.supervision.dto.query.GzrySocialWorkerQueryDTO;
import com.engine4cloud.tdf.supervision.dto.result.GzrySocialWorkerResultDTO;
import com.engine4cloud.tdf.supervision.dto.update.GzrySocialWorkerUpdateDTO;
import com.engine4cloud.tdf.supervision.entity.GzrySocialWorkerEntity;
import com.engine4cloud.tdf.supervision.mapper.GzrySocialWorkerMapper;
import com.engine4cloud.tdf.supervision.service.GzrySocialWorkerService;
import jakarta.annotation.Resource;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.Optional;

/**
 * 社会工作者
 *
 * @author wenjie
 * @date 2024-04-15 11:35:08
 */
@Service
public class GzrySocialWorkerServiceImpl extends ServiceImpl<GzrySocialWorkerMapper, GzrySocialWorkerEntity> implements GzrySocialWorkerService {

    @Resource
    private RemoteDeptService remoteDeptService;

    @Override
    public PageInfo<GzrySocialWorkerResultDTO> getPageList(Params pageable, GzrySocialWorkerQueryDTO dto) {
        R<List<Long>> deptIdRemoteList = remoteDeptService.getDescendantIdList(dto.getDeptId(), SecurityConstants.FROM_IN);

        List<Long> deptIdList = RetOps.of(deptIdRemoteList).getData().filter(CollectionUtils::isNotEmpty)
                .orElseThrow(() -> new ValidateCodeException("没有数据权限!"));

        IPage<GzrySocialWorkerResultDTO> page = this.baseMapper.pageList(Pages.page(pageable), dto, deptIdList);
        return Pages.convert(page);
    }

    @Override
    public GzrySocialWorkerResultDTO getById(Long id) {
        return GzrySocialWorkerConvert.INSTANCE.convert(super.getById(id));
    }

    @Override
    public Boolean create(GzrySocialWorkerCreateDTO dto) {
        Boolean identityUnique = this.checkUniqueByIdentity(new IdentityUniqueCheckDTO(dto.getSfzh()));
        if (!identityUnique) {
            throw new ValidateCodeException("证件号已存在");
        }

        Boolean mobileUnique = this.checkUniqueByMobile(new MobileUniqueCheckDTO(dto.getSj()));
        if (!mobileUnique) {
            throw new ValidateCodeException("手机号已存在");
        }

        TdfUser user = SecurityUtils.getUser();
        //设置所属部门
        SysDept dept = RetOps.of(remoteDeptService.detail(user.getDeptId(), SecurityConstants.FROM_IN)).getData()
                .orElseThrow(() -> new ValidateCodeException("没有数据权限!"));
        return super.save(GzrySocialWorkerConvert.INSTANCE.create(dto, dept, user.getTenantId()));
    }

    @Override
    public Boolean update(GzrySocialWorkerUpdateDTO dto) {
        GzrySocialWorkerEntity old = Optional.ofNullable(this.baseMapper.selectById(dto.getId()))
                .orElseThrow(() -> new ValidateCodeException("数据不存在"));

        Boolean identityUnique = this.checkUniqueByIdentity(new IdentityUniqueCheckDTO(old.getId(), dto.getSfzh()));
        if (!identityUnique) {
            throw new ValidateCodeException("身份证号已存在");
        }

        Boolean mobileUnique = this.checkUniqueByMobile(new MobileUniqueCheckDTO(old.getId(), dto.getSj()));
        if (!mobileUnique) {
            throw new ValidateCodeException("手机号已存在");
        }

        return updateById(GzrySocialWorkerConvert.INSTANCE.update(dto));
    }

    @Override
    public Boolean checkUniqueByIdentity(IdentityUniqueCheckDTO dto) {
        GzrySocialWorkerQueryDTO query = new GzrySocialWorkerQueryDTO();
        query.setSfzh(dto.getIdentity());
        Optional<GzrySocialWorkerEntity> optional = Optional.ofNullable(getOne(wrapper(query)));
        return optional.map(dx -> Objects.equals(dx.getId(), dto.getId())).orElse(true);
    }

    @Override
    public Boolean checkUniqueByMobile(MobileUniqueCheckDTO dto) {
        GzrySocialWorkerQueryDTO query = new GzrySocialWorkerQueryDTO();
        query.setSj(dto.getMobile());
        Optional<GzrySocialWorkerEntity> optional = Optional.ofNullable(getOne(wrapper(query)));
        return optional.map(dx -> Objects.equals(dx.getId(), dto.getId())).orElse(true);
    }

    private LambdaQueryWrapper<GzrySocialWorkerEntity> wrapper(GzrySocialWorkerQueryDTO query) {
        LambdaQueryWrapper<GzrySocialWorkerEntity> wrapper = Queries.lambda();
        Queries.accept(query.getId(), v -> wrapper.eq(GzrySocialWorkerEntity::getId, v));
        Queries.accept(query.getRybm(), v -> wrapper.eq(GzrySocialWorkerEntity::getRybm, v));
        Queries.accept(query.getSj(), v -> wrapper.eq(GzrySocialWorkerEntity::getSj, v));
        Queries.accept(query.getSfzh(), v -> wrapper.eq(GzrySocialWorkerEntity::getSfzh, v));
        return wrapper;
    }

}